import React, { Component } from 'react'
import { Table, Button, Modal, Form, Input, Tree, message } from 'antd'
import {connect} from 'react-redux'
import {logout} from '../../redux/actions'
import {Roles, addRole, updateRole} from '../../api/role'
import storageUtils from '../../utils/storageUtils'
import {formateDate} from '../../utils/dateUtils'
import menuConfig from '../../config/menuConfig'
const { TreeNode } = Tree

class Role extends Component{
  state = {
    roles: [], // 角色列表
    roleName: '', // 选中的角色
    menus: [], // 选中角色的权限列表
    visible: false, // 添加用户弹窗
    roleModal: false // 添加权限弹窗
  }
  componentDidMount() {
    this.getRoles()
  }
  componentWillMount () {
    this.treeNodes = this.getTreeNodes(menuConfig)
  }
  // 循环得到权限树
  getTreeNodes = (menuList) => {
    return menuList.reduce((pre, item) => {
      pre.push(
        <TreeNode title={item.title} key={item.key}>
          {item.children ? this.getTreeNodes(item.children) : null}
        </TreeNode>
      )
      return pre
    }, [])
  }
  // 获取角色列表
  getRoles = async ()=> {
    const result = await Roles()
    if(result.status === 0){
      const roles = result.data
      this.setState({
        roles
      })
    } else {
      message.error('获取列表失败')
    }
  }
  // 选中某个node时的回调
  onCheck = checkedKeys => {
    this.setState({
      menus: checkedKeys
    });
  };
  updateRole = (data) => {
    this.setState({
      menus: data.menus,
      roleName: data.name,
      roleModal: true
    })
  }
  columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },{
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (create_time) => formateDate(create_time)
    },{
      title: '授权时间',
      dataIndex: 'auth_time',
      key: 'auth_time',
      render: (auth_time) => formateDate(auth_time)
    },{
      title: '授权人',
      dataIndex: 'auth_name',
      key: 'auth_name'
    },{
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button type="primary" size="small" onClick={this.updateRole.bind(this, text)}>修改</Button>
        </span>
      ),
    }
  ]
  showModal = () => {
    this.setState({
      visible: true,
    });
  }
  // 提交新增角色
  handleOk = e => {
    // 进行表单验证, 只能通过了才向下处理
    this.props.form.validateFields(async (error, values) => {
      if(!error){
        this.setState({
          visible: false
        })
        // 请求添加
        const result = await addRole(values)
        if(result.status === 0){
          message.success('添加角色成功')
          // 新产生的角色
          const role = result.data
          // 更新roles状态: 基于原本状态数据更新
          this.setState(state => ({
            roles: [...state.roles, role]
          }))
        }
      }
    })
  }
  // 提交权限
  roleOk = async() => {
    this.setState({
      roleModal: false
    })
    const role = {}
    role.menus = this.state.menus
    role.auth_time = Date.now()
    role.auth_name = storageUtils.getUser().username
    const result = await updateRole(role)
    if(result.status === 0){
      message.success('设置角色权限成功')
    }
  }
  handleCancel = e => {
    this.setState({
      visible: false,
      roleModal: false,
      menus: []
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form
    return (
      <div calssName="role">
        <Button type="primary" style={{marginBottom:'10px'}} onClick={this.showModal}>添加角色</Button>
        <Table dataSource={this.state.roles} columns={this.columns} rowKey={row=>row._id} />
        <Modal title="添加角色" visible={this.state.visible} onOk={this.handleOk} onCancel={this.handleCancel}>
          <Form layout="inline">
            <Form.Item label="角色名称">
              {
                getFieldDecorator('roleName', {
                  initialValue: '',
                  rules: [
                    {required: true, message: '角色名称必须输入'}
                  ]
                })(
                  <Input placeholder='请输入角色名称' />
                )
              }
            </Form.Item>
          </Form>
        </Modal>
        <Modal title="添加权限" visible={this.state.roleModal} onOk={this.roleOk} onCancel={this.handleCancel}>
          <Form layout="inline">
            <Form.Item label="角色名称">
              <Input placeholder='请输入角色名称' value={this.state.roleName} disabled/>
            </Form.Item>
          </Form>
          <Tree checkable defaultExpandAll={true} checkedKeys={this.state.menus} onCheck={this.onCheck}>
            <TreeNode title="平台权限" key="all">
              {this.treeNodes}
            </TreeNode>
          </Tree>
        </Modal>
      </div>
    )
  }
}
export default connect(
  state => ({
    user: state.user
  }),
  {logout}
)(Form.create()(Role))